<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" ref="queryRef" label-width="100">
          <el-form-item label="规则描述：" prop="ruleName">
            <el-input v-model="queryParams.ruleName" placeholder="请输入检测项目" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-row>
            <el-col :span="18">
              <el-form-item label="检测类别组：" prop="jclbGroupId">
                <el-select v-model="queryParams.jclbGroupId" clearable filterable style="width: 100%">
                  <el-option v-for="item in jclbGroupList" :key="item.pJclbId" :value="item.pJclbId"
                    :label="item.jclbGroupName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery" class="business resetBtn">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">规则列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <div>
            <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
          </div>
        </el-row>

        <el-table class="business" ref="mainTableRef" v-loading="loading" :data="pagerTable" @row-click="rowClick"
          :row-class-name="tableRowClass">
          <el-table-column label="规则描述" align="center" prop="ruleName" />
          <el-table-column label="检测类别组" align="center" prop="jclbGroupName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
            <template #default="scope">
              <el-button link type="success" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-scrollbar ref="scrollbarRef" :height="getHeight">
        <el-form :model="form" :rules="rules" ref="serialRef" label-width="100">
          <p class="pinformation">基础信息</p>
          <el-row>
            <el-col :span="22">
              <el-form-item label="规则描述：" prop="ruleName">
                <el-input v-model="form.ruleName" :rows="3" type="textarea" placeholder="请输入规则描述" />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center; margin-top: 20px">
              <el-button type="success" @click="submitForm(false)">保存</el-button>
            </el-col>
          </el-row>
          <el-row style="justify-content: space-between">
            <el-col :span="12">
              <el-form-item label="检测类别组：" prop="jclbGroupId">
                <el-select v-model="form.jclbGroupId" clearable filterable style="width: 100%" @change="jclbGroupChange">
                  <el-option v-for="item in jclbGroupList" :key="item.jclbId" :value="item.jclbId"
                    :label="item.jclbName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="判断条件：" prop="conditionValues">
                <el-select v-model="form.conditionValues" clearable filterable style="width: 100%" multiple collapse-tags
                  collapse-tags-tooltip :max-collapse-tags="3">
                  <el-option v-for="item in data_rule_condition" :key="item.value" :value="parseInt(item.value)"
                    :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <p class="pinformation" style="margin-top: 8px">数据参数列表</p>
            <p class="totalStyle" style="margin-top: 5px">
              共 {{ DataRuleConfigList.length }} 条数据
            </p>
            <el-row style="margin-left: 20px">
              <el-button type="success" link icon="Plus" @click="addRecordButton">新增</el-button>
            </el-row>
          </el-row>
          <el-table ref="sub1TableRef" :data="DataRuleConfigList">
            <el-table-column label="参数名称" align="center" prop="paramName">
              <template #default="scope">
                <el-button link @click="insert(scope.row.paramName, scope.row.paramId)">{{ scope.row.paramName
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="检测类别" align="center" prop="jclbName" />
            <el-table-column label="点位属性" align="center" prop="propertyName" />
            <el-table-column label="检测项目组" align="center" prop="groupName" />
            <el-table-column label="检测项目" align="center" prop="jcxmName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
              <template #default="scope">
                <el-button link type="success" @click="editDataRuleConfigList(scope.row)">编辑</el-button>
                <el-button link type="success" @click="copyDataRuleConfigList(scope.row)">引用</el-button>
                <el-button link type="success" @click="deleteDataRuleConfigList(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row style="margin: 5px 0; justify-content: space-between">
            <p class="pinformation" style="margin-top: 10px">规则</p>
            <el-button @click="saveRule" type="success" :disabled="!form.ruleId">保存</el-button>
          </el-row>
          <div style="
            width: 100%;
            height: 200px;
            border: 1px solid #dcdfe6;
            border-radius: 5px;
            padding: 5px;
            text-rendering: optimizeLegibility;
          " :contentEditable="!!form.ruleId" class="formula_assembled"></div>
          <el-row style="justify-content: space-between">
            <div v-for="item in mathArray">
              <el-button :disabled="!form.ruleId" type="success" class="formula_but" @click="insert(item.value)"
                style="width: 80px; margin-top: 5px">{{ item.label }}</el-button>
            </div>
          </el-row>
        </el-form>
      </el-scrollbar>

      <el-dialog :class="'el-dialog-theme3'" :title="ysjlTitle" v-model="ysjlOpen" append-to-body
        draggable :close-on-click-modal="false" @close="dialogClose1">
        <el-form :model="addRecordsForm" label-width="85" :rules="dialogRules" ref="mbFormRef">
          <el-form-item label="参数名称：" prop="paramName">
            <el-input v-model="addRecordsForm.paramName" placeholder="请输入参数名称" clearable />
          </el-form-item>
          <el-form-item label="检测类别组：" prop="jclbGroupId">
            {{
              proxy.getItemByArray(
                jclbGroupList,
                "jclbId",
                form.jclbGroupId,
                "jclbName"
              )
            }}
          </el-form-item>
          <el-form-item label="检测类别：" prop="jclbId">
            <el-select v-model="addRecordsForm.jclbId" clearable filterable style="width: 100%" @change="jclbChange">
              <el-option v-for="item in jclbList" :key="item.jclbId" :value="item.jclbId"
                :label="item.jclbName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="点位属性：" prop="propertyId">
            <el-select clearable v-model="addRecordsForm.propertyId" style="width: 100%">
              <el-option v-for="item in sxList" :key="item.propetyId" :label="item.propertyName"
                :value="item.propetyId" />
            </el-select>
          </el-form-item>
          <el-form-item label="检测项目组：" prop="jcxmGroupId">
            <el-select v-model="addRecordsForm.jcxmGroupId" clearable filterable style="width: 100%"
              @change="jcxmGroupChange">
              <el-option v-for="item in jcxmGroupList" :key="item.groupId" :value="item.groupId"
                :label="item.groupName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检测项目：" prop="jcxmId">
            <el-select v-model="addRecordsForm.jcxmId" filterable remote clearable reserve-keyword remote-show-suffix
              :remote-method="remoteMethod" :loading="loading2" style="width: 100%">
              <el-option v-for="item in jcxmList" :key="item.jcxmId" :value="item.jcxmId" :label="item.jcxmName">
                <span v-html="proxy.getSupAndSub(item.jcxmName)"></span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="save1" type="success">保 存</el-button>
            <el-button @click="ysjlOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup name="ReasonRule">
import {
  dataRuleList,
  getDataRuleForm,
  delDataRule,
  addDataRule,
  listDataRuleConfig,
  addRecordsConfig,
  delRecordsConfig,
  getRecordsConfigForm,
  addRule,
  ruleList,
  getJcxmList,
} from "@/api/system/reasonRule";
import {
  allListJclbGroup,
  pJclbIdByJclb,
  getSxJclb,
  jclbByJcxmGroup,
} from "@/api/store/jclb";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const total = ref(0);
const mathArray = ref([
  { label: "加", value: "+" },
  { label: "减", value: "-" },
  { label: "乘", value: "*" },
  { label: "除", value: "/" },
  { label: "左括号", value: "(" },
  { label: "右括号", value: ")" },
  { label: "大于", value: ">" },
  { label: "小于", value: "<" },
  { label: "大于等于", value: "≥" },
  { label: "小于等于", value: "≤" },
  { label: "等于", value: "=" },
  { label: "且", value: "且" },
  { label: "或", value: "或" },
  { label: "则", value: "则" },
]);
const pagerTable = ref([]);
const DataRuleConfigList = ref([]);
const { data_rule_condition } = proxy.useDict("data_rule_condition");
const data = reactive({
  form: {},
  addRecordsForm: { templateList: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    jclbGroupId: [
      {
        required: true,
        message: "检测类别组不能为空",
        trigger: "blur",
      },
    ],
    ruleName: [
      {
        required: true,
        message: "规则描述不能为空",
        trigger: "blur",
      },
    ],
  },
  dialogRules: {
    paramName: [
      { required: true, message: "参数名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules, addRecordsForm, dialogRules } = toRefs(data);

/** 查询流水号配置列表 */
function getList() {
  loading.value = true;
  dataRuleList(queryParams.value).then((response) => {
    pagerTable.value = response.data;
    total.value = pagerTable.value.length;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("serialRef");
  document.querySelector(".formula_assembled").innerText = "";
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const jclbGroupId = ref("");
const ruleForm = ref({});

/** 修改按钮操作 */
function rowClick(row) {
  reset();
  ruleForm.value = {};
  DataRuleConfigList.value = [];
  jclbGroupId.value = "";
  getDataRuleForm(row.ruleId).then((response) => {
    heightBright.value = row.ruleId;
    form.value = response.data;
    jclbGroupId.value = form.value.jclbGroupId;
    jclbGroupChange(form.value.jclbGroupId);
    getDataRuleList();
    getRuleList(row.ruleId);
  });
}

function getRuleList(ruleId) {
  ruleList({ ruleId: ruleId }).then((res) => {
    ruleForm.value = res.data || {};
    nextTick(() => {
      if (ruleForm.value.formulaExpress) {
        const divElement = document.querySelector(".formula_assembled");
        if (ruleForm.value.formulaExpress.charAt(0) === "φ") {
          ruleForm.value.formulaExpress =
            ruleForm.value.formulaExpress.slice(1);
        }
        let expressList = ruleForm.value.formulaExpress.split("φ");
        expressList.forEach((item) => {
          let isComponent = item.split("Ψ");
          if (isComponent.length > 1) {
            let spanElement = document.createElement("span");
            spanElement.setAttribute("paramId", isComponent[0]);
            spanElement.setAttribute("contenteditable", "false");
            spanElement.textContent = isComponent[1];
            spanElement.className = "to_show_span";
            divElement.appendChild(spanElement);
          } else {
            let textNode = document.createTextNode(item);
            divElement.appendChild(textNode);
          }
        });
      }
    });
  });
}

/** 提交按钮 */
function submitForm(isAuto) {
  return new Promise((resolve) => {
    proxy.$refs["serialRef"].validate((valid) => {
      if (valid) {
        addDataRule(form.value).then((res) => {
          if (!isAuto) {
            proxy.$modal.msgSuccess(res.msg);
          }
          form.value.ruleId = res.data;
          heightBright.value = res.data;
          getList();
          resolve();
        });
      }
    });
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ruleId = row.ruleId;
  proxy.$modal
    .confirm("是否确认删除此数据项？")
    .then(function () {
      return delDataRule(ruleId);
    })
    .then(() => {
      getList();
      handleAdd();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function save1() {
  proxy.$refs["mbFormRef"].validate((valid) => {
    if (valid) {
      addRecordsForm.value.jclbGroupId = form.value.jclbGroupId;
      addRecordsForm.value.ruleId = form.value.ruleId;
      addRecordsConfig(addRecordsForm.value).then((res) => {
        ysjlOpen.value = false;
        proxy.$modal.msgSuccess(res.msg);
        getDataRuleList();
      });
    }
  });
}

function getDataRuleList() {
  listDataRuleConfig({ ruleId: form.value.ruleId }).then((res) => {
    DataRuleConfigList.value = res.data;
  });
}

const ysjlOpen = ref(false);
const ysjlTitle = ref("新增数据参数");

function addRecordButton() {
  submitForm(true).then(() => {
    ysjlOpen.value = true;
    ysjlTitle.value = "新增数据参数";
  });
}

function deleteDataRuleConfigList(row) {
  proxy.$modal
    .confirm("是否确认删除此条数据项？")
    .then(function () {
      return delRecordsConfig(row.paramId);
    })
    .then(() => {
      getDataRuleList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function editDataRuleConfigList(row) {
  return new Promise((resolve, reject) => {
    getRecordsConfigForm(row.paramId).then((res) => {
      addRecordsForm.value = res.data;
      resolve()
      jclbChange(addRecordsForm.value.jclbId, true);
      ysjlOpen.value = true;
      jcxmList.value = [{ jcxmName: res.data.jcxmName, jcxmId: res.data.jcxmId }];
      ysjlTitle.value = "编辑数据参数";
    });
  })
}

function copyDataRuleConfigList(row) {
  editDataRuleConfigList(row).then(res => {
    addRecordsForm.value.paramId = ""
  })
}

function handleAdd() {
  ruleForm.value = {};
  DataRuleConfigList.value = [];
  addRecordsForm.value = {};
  heightBright.value = "";
  proxy.resetForm("serialRef");
  form.value = {};
  let divElement = document.querySelector(".formula_assembled");
  if (divElement) {
    divElement.innerText = "";
  }
}

function dialogClose1() {
  addRecordsForm.value = {};
  proxy.$refs.mbFormRef.clearValidate();
}

getList();

//   -----------------------------------------复制功能---------------------------------------

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 74 },
        { tableName: "sub1", bottomHeight: 300 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub1", bottomHeight: 300 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub1", bottomHeight: 300 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.ruleId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

function getRange() {
  const selection = window.getSelection();
  const range = document.createRange();
  if (selection.getRangeAt && selection.rangeCount > 0) {
    return { range: selection.getRangeAt(0), selection };
  }
  const formulaAssemble = document.querySelector(".formula_assembled");
  range.selectNodeContents(formulaAssemble);
  range.collapse(false);
  return { range: range, selection };
}

function getSpan(className, text, id) {
  if (id) {
    const span = document.createElement("span");
    span.className = className;
    span.innerText = text;
    span.setAttribute("contenteditable", "false");
    span.setAttribute("paramId", id);
    return span;
  } else {
    return document.createTextNode(text);
  }
}

function insert(num, id) {
  const { range } = getRange();
  const span = getSpan("to_show_span", num, id);

  const formulaAssemble = document.querySelector(".formula_assembled");

  if (
    range.commonAncestorContainer === formulaAssemble ||
    (range.commonAncestorContainer.nodeType === Node.TEXT_NODE &&
      range.commonAncestorContainer.parentNode === formulaAssemble)
  ) {
    range.insertNode(span);
  } else {
    let lastChild = formulaAssemble.lastElementChild;
    if (!lastChild) {
      lastChild = formulaAssemble.lastChild;
    }
    if (lastChild && lastChild.nodeType === Node.TEXT_NODE) {
      formulaAssemble.insertBefore(span, lastChild.nextSibling);
    } else {
      formulaAssemble.appendChild(span);
    }
  }

  const newRange = document.createRange();
  newRange.setStartAfter(span);
  newRange.setEndAfter(span);

  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(newRange);

  formulaAssemble.focus();
}

const jclbList = ref([]);
const jclbGroupList = ref([]);

allListJclbGroup().then((res) => {
  jclbGroupList.value = res.data;
});

function jclbGroupChange(val) {
  if (DataRuleConfigList.value.length > 0 && jclbGroupId.value != val) {
    proxy.$modal
      .confirm("更换检测类别组将会删除数据参数列表关联的检测类别、检测项目等！")
      .then(() => {
        jcxmList.value = [];
        addRecordsForm.value.jcxmId = "";
        jcxmList.value = [];
        jclbList.value = [];
        sxList.value = [];
        jcxmGroupList.value = [];
        addRecordsForm.value.jcxmId = "";
        addRecordsForm.value.propertyId = "";
        addRecordsForm.value.jcxmGroupId = "";
        addRecordsForm.value.jclbId = "";
        if (val) {
          pJclbIdByJclb({ pJclbId: val }).then((res) => {
            jclbList.value = res.data;
          });
        }
        getDataRuleList();
      })
      .catch(() => {
        form.value.jclbGroupId = jclbGroupId.value;
      });
  } else {
    jcxmList.value = [];
    addRecordsForm.value.jcxmId = "";
    jcxmList.value = [];
    jclbList.value = [];
    sxList.value = [];
    jcxmGroupList.value = [];
    addRecordsForm.value.jcxmId = "";
    addRecordsForm.value.propertyId = "";
    addRecordsForm.value.jcxmGroupId = "";
    addRecordsForm.value.jclbId = "";
    jclbGroupId.value = val;
    if (val) {
      pJclbIdByJclb({ pJclbId: val }).then((res) => {
        jclbList.value = res.data;
      });
    }
  }
}

const sxList = ref([]);

function jclbChange(val, isAuto) {
  jcxmList.value = [];
  sxList.value = [];
  jcxmGroupList.value = [];
  addRecordsForm.value.jcxmId = "";
  if (!isAuto) {
    addRecordsForm.value.propertyId = "";
    addRecordsForm.value.jcxmGroupId = "";
  }
  if (val) {
    getSxJclb({ jclbId: val }).then((res) => {
      sxList.value = res.data;
    });
    jclbByJcxmGroup(val).then((res) => {
      jcxmGroupList.value = res.data;
    });
  }
}

const jcxmList = ref([]);
const jcxmGroupList = ref([]);

function jcxmGroupChange(val) {
  jcxmList.value = [];
  addRecordsForm.value.jcxmId = "";
}

const loading2 = ref(false);

function remoteMethod(val) {
  if (val) {
    loading2.value = true;
    setTimeout(() => {
      getJcxmList({
        jcxmName: val,
        jclbGroupId: form.value.jclbGroupId,
        jclbId: addRecordsForm.value.jclbId,
        groupld: addRecordsForm.value.groupld,
      }).then((res) => {
        loading2.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  } else {
    jcxmList.value = [];
  }
}

function saveRule(params) {
  const divElement = document.querySelector(".formula_assembled");
  if (divElement.childNodes.length == 0) {
    proxy.$modal.msgError("未输入规则");
    return;
  } else {
    let next;
    for (let i = 0; i < divElement.childNodes.length; i++) {
      if (divElement.childNodes[i].data == "") {
        next = false;
      } else {
        next = true;
        break;
      }
    }
    if (!next) {
      proxy.$modal.msgError("未输入规则");
      return;
    }
    ruleForm.value.formulaExpressDisplay = "";
    divElement.childNodes.forEach((node) => {
      if (node.nodeType === Node.ELEMENT_NODE) {
        ruleForm.value.formulaExpressDisplay += node.textContent;
      } else if (node.nodeType === Node.TEXT_NODE) {
        ruleForm.value.formulaExpressDisplay += node.nodeValue;
      }
    });
    const childNodes = divElement.childNodes;
    ruleForm.value.formulaExpress = "";
    Array.from(childNodes).forEach((node) => {
      if (node instanceof HTMLSpanElement) {
        const paramId = node.getAttribute("paramId");
        if (paramId) {
          ruleForm.value.formulaExpress += paramId;
        } else {
          ruleForm.value.formulaExpress += node.innerText;
        }
      } else {
        ruleForm.value.formulaExpress += node.textContent;
      }
    });
    ruleForm.value.ruleId = form.value.ruleId;
    addRule(ruleForm.value).then((res) => {
      proxy.$modal.msgSuccess("保存成功");
    });
  }
}

function getHeight() {
  proxy.getSubFileHeight(proxy, 'scrollbarRef')
}

</script>

<style scoped lang="scss">
:deep(.to_show_span) {
  background-color: skyBlue !important;
  color: #fff !important;
  margin: 0 5px;
  border-radius: 5px;
  padding: 3px 10px;
  height: 20px;
}
</style>
